package org.particlethink.service.impl;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.particlethink.service.StorageService;

import java.io.InputStream;

public class MinioStorage implements StorageService {
	private MinioClient minioClient;
	private final String bucket;
	private final String endpoint;

	public MinioStorage(String endpoint, String accessKey, String secretKey, String bucket) {
		this.minioClient = MinioClient.builder().
				endpoint(endpoint).
				credentials(accessKey, secretKey).
				build();
		this.bucket = bucket;
		this.endpoint = endpoint;
	}


	@Override
	public String upload(String fileName, InputStream inputStream) throws Exception {
		boolean found =
				this.minioClient.bucketExists(BucketExistsArgs.builder().bucket(this.bucket).build());

		if (!found) {
			this.minioClient.makeBucket(MakeBucketArgs.builder().bucket(this.bucket).build());
		}

		// 一次最多5G
		this.minioClient.putObject(
				PutObjectArgs.builder().bucket(this.bucket).stream(inputStream, -1, 5368709120L).object(fileName).build()
		);


		// todo 返回的 url 路劲需要校验

		return endpoint + "/" + bucket + "/" + fileName;
	}
}
